package com.library.service.impl;

import com.library.dao.BookDao;
import com.library.model.Book;
import com.library.service.BookService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

@Service
public class BookServiceImpl implements BookService {

    private final BookDao bookDao;

    public BookServiceImpl(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    @Override
    public List<Book> getAllBooks() {
        return bookDao.findAll();
    }

    @Override
    public List<Book> getBooksByCriteria(Map<String, Object> criteria) {
        return bookDao.findByCriteria(criteria);
    }

    @Override
    public Book getBookById(Long id) {
        return bookDao.findById(id);
    }

    @Override
    public Book getBookByIsbn(String isbn) {
        return bookDao.findByIsbn(isbn);
    }

    @Override
    public boolean addBook(Book book) {

        if (bookDao.findByIsbn(book.getIsbn()) != null) {
            return false;
        }
        return bookDao.save(book) > 0;
    }

    @Override
    public boolean updateBook(Book book) {

        Book existingBook = bookDao.findById(book.getId());
        if (existingBook == null) {
            return false;
        }

        if (!existingBook.getIsbn().equals(book.getIsbn()) &&
                bookDao.findByIsbn(book.getIsbn()) != null) {
            return false;
        }

        return bookDao.update(book) > 0;
    }

    @Override
    public boolean deleteBook(Long id) {

        if (bookDao.findById(id) == null) {
            return false;
        }
        return bookDao.delete(id) > 0;
    }
}
